package cn.iocoder.yudao.framework.region;

import cn.hutool.core.io.resource.ResourceUtil;
import cn.hutool.json.JSONUtil;
import cn.iocoder.yudao.framework.region.bo.CityNode;
import cn.iocoder.yudao.framework.region.enums.CityDataSet;
import cn.iocoder.yudao.framework.region.enums.RegionDataSet;
import cn.iocoder.yudao.framework.region.enums.RegionType;
import cn.iocoder.yudao.framework.region.vo.CityVO;
import lombok.experimental.UtilityClass;

import java.util.ArrayList;
import java.util.List;

/**
 * <pre>
 * OOoO0OOoO0OOOooo0oOOOO0OOOOO0oooOO0ooOOO0Ooooo0OOOOo0ooooO0OOooo0Ooooo0OOOOO
 *  中国城市工具类
 * OOoO0OOoO0OOOooo0oOOOO0OOOOO0oooOO0ooOOO0Ooooo0OOOOo0ooooO0OOooo0Ooooo0OOOOO
 * </pre>
 *
 * @author 山野羡民（1032694760@qq.com）
 * @since 2025/05/17
 */
@UtilityClass
public class CityUtils {
    private static final String ADAPAY_JSON = "city_adapay.json";

    public List<CityVO> getList(CityDataSet dataSet) {
        if (dataSet == CityDataSet.Adapay) {
            return getListByAdapay();
        }
        return getListBySpider();
    }

    public static List<CityVO> getListBySpider() {
        return RegionUtils.getRegionListByType(RegionDataSet.ONLY_LATEST, RegionType.CITY, region -> {
            CityVO cityVO = new CityVO();
            cityVO.setCityCode(region.getCode());
            cityVO.setCityName(region.getShortName());
            return cityVO;
        });
    }

    public static List<CityVO> getListByAdapay() {
        List<CityVO> list = new ArrayList<>();
        String adapayJson = ResourceUtil.readUtf8Str(ADAPAY_JSON);
        List<CityNode> cityNodes = JSONUtil.parseArray(adapayJson).toList(CityNode.class);
        for (CityNode provinceNode : cityNodes) {
            if (provinceNode.getCities() == null) {
                continue;
            }
            for (CityNode cityNode : provinceNode.getCities()) {
                CityVO cityVO = new CityVO();
                cityVO.setCityCode(cityNode.getValue());
                cityVO.setCityName(cityNode.getTitle()
                        .replaceAll("省", "") // 台湾省
                        .replaceAll("市", "") // 四个直辖市
                        .replaceAll("特别行政区", "")); // 港澳特别行政区
                list.add(cityVO);
            }
        }
        return list;
    }

}
